import pygame
import math
from bird import Bird
from game_objects import GameObject
from particles import ParticleSystem
from sound_manager import SoundManager
from levels import LevelManager
from menu import LevelSelector

# 初始化Pygame
pygame.init()
pygame.mixer.init()

# 游戏常量
WINDOW_WIDTH = 1024
WINDOW_HEIGHT = 768
FPS = 60

# 颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BROWN = (139, 69, 19)
SKY_COLOR = (135, 206, 235)
GRASS_COLOR = (34, 139, 34)

# 弹弓常量
SLING_X = 200
SLING_Y = 500
SLING_WIDTH = 40
SLING_HEIGHT = 120

class GameState:
    MENU = "menu"
    PLAYING = "playing"
    PAUSED = "paused"
    LEVEL_COMPLETE = "level_complete"

class Game:
    def __init__(self):
        self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
        pygame.display.set_caption("愤怒的小鸟")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 36)
        self.running = True
        
        # 初始化系统
        self.particle_system = ParticleSystem()
        self.sound_manager = SoundManager()
        self.level_manager = LevelManager()
        self.level_selector = LevelSelector(WINDOW_WIDTH, WINDOW_HEIGHT, self.level_manager)
        
        # 游戏状态
        self.state = GameState.MENU
        self.reset_game()

    def reset_game(self):
        """重置当前关卡"""
        self.bird = Bird(SLING_X, SLING_Y)
        self.objects = self.level_manager.get_current_level().objects.copy()
        self.dragging = False
        self.pull_x = SLING_X
        self.pull_y = SLING_Y
        self.score = 0
        self.shots_taken = 0
        self.level_complete = False
        self.particle_system = ParticleSystem()

    def handle_events(self):
        """处理游戏事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False
                return

            if self.state == GameState.MENU:
                result = self.level_selector.handle_event(event)
                if result == "start_game":
                    self.state = GameState.PLAYING
                    self.reset_game()
                elif result == "back":
                    pass  # 处理返回按钮
            
            elif self.state == GameState.PLAYING:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    if (not self.bird.is_flying and 
                        abs(mouse_x - SLING_X) < 20 and 
                        abs(mouse_y - SLING_Y) < 20):
                        self.dragging = True
                        self.sound_manager.play('bird')
                
                elif event.type == pygame.MOUSEBUTTONUP:
                    if self.dragging:
                        self.dragging = False
                        self.bird.launch(SLING_X, SLING_Y, self.pull_x, self.pull_y)
                        self.shots_taken += 1
                        self.sound_manager.play('launch')
                
                elif event.type == pygame.MOUSEMOTION:
                    if self.dragging:
                        self.pull_x, self.pull_y = pygame.mouse.get_pos()
                        # 限制拉动距离
                        dx = self.pull_x - SLING_X
                        dy = self.pull_y - SLING_Y
                        distance = math.sqrt(dx * dx + dy * dy)
                        if distance > 100:
                            angle = math.atan2(dy, dx)
                            self.pull_x = SLING_X + 100 * math.cos(angle)
                            self.pull_y = SLING_Y + 100 * math.sin(angle)
                
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        self.reset_bird()
                    elif event.key == pygame.K_ESCAPE:
                        self.state = GameState.MENU
                    elif event.key == pygame.K_m:
                        self.sound_manager.toggle_sound()
            
            elif self.state == GameState.LEVEL_COMPLETE:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        if self.level_manager.next_level():
                            self.reset_game()
                            self.state = GameState.PLAYING
                        else:
                            self.state = GameState.MENU

    def reset_bird(self):
        """重置小鸟到弹弓位置"""
        if not self.level_complete:
            self.bird = Bird(SLING_X, SLING_Y)

    def update(self):
        """更新游戏状态"""
        if self.state != GameState.PLAYING:
            return

        # 更新粒子系统
        self.particle_system.update()
        
        # 更新所有游戏对象
        for obj in self.objects:
            obj.update()
        
        if self.bird.is_flying:
            # 创建小鸟飞行轨迹
            self.particle_system.create_trail(self.bird.x, self.bird.y, 
                                           (255, 200, 200))
            
            # 更新小鸟位置
            self.bird.update()
            self.bird.handle_boundary_collision(WINDOW_WIDTH, WINDOW_HEIGHT)
            
            # 检查与所有对象的碰撞
            for obj in self.objects:
                if not obj.destroyed:
                    damage = self.bird.check_collision(obj)
                    if damage > 0:
                        # 播放碰撞音效
                        self.sound_manager.play('collision')
                        
                        # 创建碰撞粒子效果
                        self.particle_system.create_impact(
                            obj.rect.centerx, obj.rect.centery,
                            obj.color, self.bird.velocity_x, self.bird.velocity_y
                        )
                        
                        # 处理伤害
                        if obj.take_damage(damage):
                            self.score += 100
                            self.sound_manager.play('break')
                            # 创建破坏粒子效果
                            self.particle_system.create_explosion(
                                obj.rect.centerx, obj.rect.centery,
                                obj.color, 30
                            )
            
            # 检查是否需要重置小鸟
            if (abs(self.bird.velocity_x) < 0.1 and 
                abs(self.bird.velocity_y) < 0.1 and 
                self.bird.y > WINDOW_HEIGHT - 30):
                self.reset_bird()
            
            # 检查关卡是否完成
            all_destroyed = all(obj.destroyed for obj in self.objects)
            if all_destroyed and not self.level_complete:
                self.level_complete = True
                self.sound_manager.play('victory')
                self.level_manager.update_level_progress(self.score)
                self.state = GameState.LEVEL_COMPLETE

    def draw_background(self):
        """绘制游戏背景"""
        # 绘制天空渐变
        for i in range(WINDOW_HEIGHT):
            progress = i / WINDOW_HEIGHT
            color = [
                int(135 + (200 - 135) * progress),  # R
                int(206 + (240 - 206) * progress),  # G
                int(235 + (255 - 235) * progress)   # B
            ]
            pygame.draw.line(self.screen, color, (0, i), (WINDOW_WIDTH, i))
        
        # 绘制远景云朵
        cloud_positions = [(100, 100), (400, 150), (700, 80)]
        for x, y in cloud_positions:
            for offset in [(0, 0), (20, -10), (40, 0)]:
                pygame.draw.circle(self.screen, WHITE,
                                 (x + offset[0], y + offset[1]), 30)
        
        # 绘制草地
        pygame.draw.rect(self.screen, GRASS_COLOR,
                        (0, WINDOW_HEIGHT - 100, WINDOW_WIDTH, 100))
        
        # 添加简单的草叶效果
        for i in range(0, WINDOW_WIDTH, 30):
            grass_height = random.randint(5, 15)
            grass_points = [
                (i, WINDOW_HEIGHT - 100),
                (i + 5, WINDOW_HEIGHT - 100 - grass_height),
                (i + 10, WINDOW_HEIGHT - 100)
            ]
            pygame.draw.polygon(self.screen, (0, 100, 0), grass_points)

    def draw(self):
        """绘制游戏画面"""
        if self.state == GameState.MENU:
            self.level_selector.draw(self.screen)
        else:
            self.draw_background()
            
            # 绘制弹弓
            pygame.draw.rect(self.screen, BROWN, 
                           (SLING_X - 5, SLING_Y, 10, SLING_HEIGHT))
            
            # 绘制弹弓橡皮筋
            if self.dragging:
                pygame.draw.line(self.screen, BROWN, 
                               (SLING_X - 20, SLING_Y), 
                               (self.pull_x, self.pull_y), 5)
                pygame.draw.line(self.screen, BROWN, 
                               (SLING_X + 20, SLING_Y), 
                               (self.pull_x, self.pull_y), 5)
            elif not self.bird.is_flying:
                pygame.draw.line(self.screen, BROWN, 
                               (SLING_X - 20, SLING_Y), 
                               (SLING_X, SLING_Y), 5)
                pygame.draw.line(self.screen, BROWN, 
                               (SLING_X + 20, SLING_Y), 
                               (SLING_X, SLING_Y), 5)
            
            # 绘制所有游戏对象
            for obj in self.objects:
                obj.draw(self.screen)
            
            # 绘制粒子效果
            self.particle_system.draw(self.screen)
            
            # 绘制小鸟
            self.bird.draw(self.screen)
            
            # 绘制得分和射击次数
            score_text = self.font.render(f'得分: {self.score}', True, BLACK)
            shots_text = self.font.render(f'射击次数: {self.shots_taken}', True, BLACK)
            self.screen.blit(score_text, (10, 10))
            self.screen.blit(shots_text, (10, 50))
            
            # 绘制关卡信息
            level = self.level_manager.get_current_level()
            level_text = self.font.render(f'关卡: {level.name}', True, BLACK)
            self.screen.blit(level_text, (WINDOW_WIDTH - 200, 10))
            
            # 绘制游戏操作提示
            if self.state == GameState.LEVEL_COMPLETE:
                if self.level_manager.current_level_index < len(self.level_manager.levels) - 1:
                    message = "按空格键进入下一关"
                else:
                    message = "恭喜通关！按空格键返回菜单"
                complete_text = self.font.render(message, True, BLACK)
                text_rect = complete_text.get_rect(center=(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2))
                self.screen.blit(complete_text, text_rect)
            elif not self.bird.is_flying and self.shots_taken > 0:
                reset_text = self.font.render("按 R 键重置小鸟", True, BLACK)
                self.screen.blit(reset_text, (WINDOW_WIDTH - 200, 50))
            
            # 绘制音效控制提示
            sound_status = "开启" if self.sound_manager.enabled else "关闭"
            sound_text = self.font.render(f'按M键切换音效 ({sound_status})', True, BLACK)
            self.screen.blit(sound_text, (WINDOW_WIDTH - 300, 90))
        
        pygame.display.flip()

    def run(self):
        """运行游戏主循环"""
        while self.running:
            self.handle_events()
            self.update()
            self.draw()
            self.clock.tick(FPS)
        
        pygame.quit()

if __name__ == "__main__":
    game = Game()
    game.run()